<th:block layout:fragment="scripts">
    <script>
        let invoices = []; // 存储发票数据
        let clients = []; // 存储客户列表
        let contracts = []; // 存储合同列表
        
        document.addEventListener('DOMContentLoaded', function() {
            loadInvoices();
            loadClients();
            loadContracts();
            
            // 设置表单提交事件
            document.getElementById('invoiceForm').addEventListener('submit', function(e) {
                e.preventDefault();
                saveInvoice();
            });
            
            // 设置搜索和筛选事件
            document.getElementById('searchInvoice').addEventListener('input', filterInvoices);
            document.getElementById('filterStatus').addEventListener('change', filterInvoices);
            document.getElementById('filterDate').addEventListener('change', filterInvoices);
        });
        
        // 从服务器加载发票列表
        function loadInvoices() {
            fetch('/api/sales/invoices/list')
                .then(response => response.json())
                .then(result => {
                    if (result.code === 200) {
                        invoices = result.data;
                        renderInvoices();
                    } else {
                        console.error('加载发票列表失败:', result.message);
                    }
                })
                .catch(error => console.error('加载发票列表失败:', error));
        }
        
        // 加载客户列表用于表单选择
        function loadClients() {
            fetch('/api/sales/clients/list')
                .then(response => response.json())
                .then(result => {
                    if (result.code === 200) {
                        clients = result.data;
                        
                        // 填充客户下拉框
                        const clientSelect = document.getElementById('clientId');
                        clientSelect.innerHTML = '<option value="">请选择客户</option>';
                        
                        clients.forEach(client => {
                            const option = document.createElement('option');
                            option.value = client.id;
                            option.textContent = client.name;
                            clientSelect.appendChild(option);
                        });
                    } else {
                        console.error('加载客户列表失败:', result.message);
                    }
                })
                .catch(error => console.error('加载客户列表失败:', error));
        }
        
        // 加载合同列表用于表单选择
        function loadContracts() {
            fetch('/api/sales/contracts/list')
                .then(response => response.json())
                .then(result => {
                    if (result.code === 200) {
                        contracts = result.data;
                        
                        // 填充合同下拉框
                        const contractSelect = document.getElementById('contractId');
                        contractSelect.innerHTML = '<option value="">请选择关联合同</option>';
                        
                        contracts.forEach(contract => {
                            const option = document.createElement('option');
                            option.value = contract.id;
                            option.textContent = contract.contractNumber + ' - ' + contract.name;
                            contractSelect.appendChild(option);
                        });
                    } else {
                        console.error('加载合同列表失败:', result.message);
                    }
                })
                .catch(error => console.error('加载合同列表失败:', error));
        }
        
        // 渲染发票列表
        function renderInvoices() {
            const table = document.getElementById('invoices-table');
            const tbody = table.querySelector('tbody');
            tbody.innerHTML = '';
            
            if (invoices.length === 0) {
                const emptyRow = document.createElement('tr');
                emptyRow.innerHTML = '<td colspan="8" class="text-center">没有找到发票数据</td>';
                tbody.appendChild(emptyRow);
                return;
            }
            
            invoices.forEach(invoice => {
                const row = document.createElement('tr');
                
                // 设置状态样式
                let statusClass = '';
                switch(invoice.status) {
                    case 'DRAFT': statusClass = 'badge-secondary'; break;
                    case 'SENT': statusClass = 'badge-info'; break;
                    case 'PAID': statusClass = 'badge-success'; break;
                    case 'OVERDUE': statusClass = 'badge-danger'; break;
                    case 'CANCELED': statusClass = 'badge-dark'; break;
                }
                
                // 获取状态对应的显示文本
                const statusText = {
                    'DRAFT': '草稿',
                    'SENT': '已发送',
                    'PAID': '已付款',
                    'OVERDUE': '已逾期',
                    'CANCELED': '已取消'
                }[invoice.status] || invoice.status;
                
                row.innerHTML = `
                    <td>${invoice.id}</td>
                    <td>${invoice.invoiceNumber || '-'}</td>
                    <td>${invoice.clientName || '-'}</td>
                    <td>${invoice.amount.toLocaleString('zh-CN', {style: 'currency', currency: 'CNY'})}</td>
                    <td>${invoice.issueDate || '-'}</td>
                    <td>${invoice.dueDate || '-'}</td>
                    <td><span class="badge ${statusClass}">${statusText}</span></td>
                    <td>
                        <button class="btn btn-sm btn-info" onclick="viewInvoice(${invoice.id})">查看</button>
                        <button class="btn btn-sm btn-primary" onclick="editInvoice(${invoice.id})">编辑</button>
                        <button class="btn btn-sm btn-danger" onclick="deleteInvoice(${invoice.id})">删除</button>
                    </td>
                `;
                
                tbody.appendChild(row);
            });
        }
        
        function showAddInvoiceModal() {
            document.getElementById('modalTitle').textContent = '添加发票';
            document.getElementById('invoiceForm').reset();
            
            // 移除可能存在的ID
            document.getElementById('invoiceForm').removeAttribute('data-id');
            
            // 当前日期作为默认值
            const today = new Date().toISOString().split('T')[0];
            document.getElementById('issueDate').value = today;
            
            // 默认到期日为30天后
            const dueDate = new Date();
            dueDate.setDate(dueDate.getDate() + 30);
            document.getElementById('dueDate').value = dueDate.toISOString().split('T')[0];
            
            // 显示模态框
            document.getElementById('invoiceModal').style.display = 'block';
        }
        
        function closeModal() {
            document.getElementById('invoiceModal').style.display = 'none';
        }
        
        function editInvoice(invoiceId) {
            document.getElementById('modalTitle').textContent = '编辑发票';
            
            // 获取发票详情
            fetch(`/api/sales/invoices/${invoiceId}`)
                .then(response => response.json())
                .then(result => {
                    if (result.code === 200) {
                        const invoice = result.data;
                        
                        // 填充表单
                        document.getElementById('invoiceNumber').value = invoice.invoiceNumber || '';
                        document.getElementById('clientId').value = invoice.clientId || '';
                        document.getElementById('contractId').value = invoice.contractId || '';
                        document.getElementById('amount').value = invoice.amount;
                        document.getElementById('issueDate').value = invoice.issueDate || '';
                        document.getElementById('dueDate').value = invoice.dueDate || '';
                        document.getElementById('status').value = invoice.status;
                        document.getElementById('notes').value = invoice.notes || '';
                        
                        // 设置表单ID用于保存
                        document.getElementById('invoiceForm').setAttribute('data-id', invoice.id);
                        
                        // 更新客户关联的合同
                        if (invoice.clientId) {
                            loadClientContracts(invoice.clientId, invoice.contractId);
                        }
                        
                        // 显示模态框
                        document.getElementById('invoiceModal').style.display = 'block';
                    } else {
                        console.error('加载发票详情失败:', result.message);
                    }
                })
                .catch(error => console.error('加载发票详情失败:', error));
        }
        
        function viewInvoice(invoiceId) {
            // 跳转到发票详情页面
            window.location.href = `/sales/invoices/${invoiceId}`;
        }
        
        function deleteInvoice(invoiceId) {
            if (confirm('确定要删除这个发票吗？')) {
                fetch(`/api/sales/invoices/delete/${invoiceId}`, {
                    method: 'DELETE'
                })
                .then(response => response.json())
                .then(result => {
                    if (result.code === 200) {
                        // 刷新发票列表
                        loadInvoices();
                    } else {
                        alert('删除发票失败: ' + result.message);
                    }
                })
                .catch(error => {
                    console.error('删除发票失败:', error);
                    alert('系统错误，请稍后重试');
                });
            }
        }
        
        function saveInvoice() {
            const form = document.getElementById('invoiceForm');
            const invoiceId = form.getAttribute('data-id');
            const isEdit = !!invoiceId;
            
            // 表单验证
            if (!form.checkValidity()) {
                form.reportValidity();
                return;
            }
            
            const invoiceData = {
                invoiceNumber: document.getElementById('invoiceNumber').value,
                clientId: document.getElementById('clientId').value || null,
                contractId: document.getElementById('contractId').value || null,
                amount: parseFloat(document.getElementById('amount').value),
                issueDate: document.getElementById('issueDate').value || null,
                dueDate: document.getElementById('dueDate').value || null,
                status: document.getElementById('status').value,
                notes: document.getElementById('notes').value
            };
            
            if (isEdit) {
                invoiceData.id = parseInt(invoiceId);
            }
            
            const url = isEdit ? '/api/sales/invoices/update' : '/api/sales/invoices/add';
            const method = isEdit ? 'PUT' : 'POST';
            
            fetch(url, {
                method: method,
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(invoiceData)
            })
            .then(response => response.json())
            .then(result => {
                if (result.code === 200) {
                    // 关闭模态框，重新加载发票列表
                    closeModal();
                    loadInvoices();
                } else {
                    alert('保存发票失败: ' + result.message);
                }
            })
            .catch(error => {
                console.error('保存发票失败:', error);
                alert('系统错误，请稍后重试');
            });
        }
        
        function filterInvoices() {
            const searchTerm = document.getElementById('searchInvoice').value.toLowerCase();
            const statusFilter = document.getElementById('filterStatus').value;
            const dateFilter = document.getElementById('filterDate').value;
            
            // 构建过滤条件
            const params = new URLSearchParams();
            if (searchTerm) params.append('search', searchTerm);
            if (statusFilter) params.append('status', statusFilter);
            if (dateFilter) params.append('date', dateFilter);
            
            // 发送带参数的请求
            fetch(`/api/sales/invoices/list?${params.toString()}`)
                .then(response => response.json())
                .then(result => {
                    if (result.code === 200) {
                        invoices = result.data;
                        renderInvoices();
                    } else {
                        console.error('筛选发票失败:', result.message);
                    }
                })
                .catch(error => console.error('筛选发票失败:', error));
        }
        
        function resetFilters() {
            document.getElementById('searchInvoice').value = '';
            document.getElementById('filterStatus').value = '';
            document.getElementById('filterDate').value = '';
            loadInvoices(); // 重新加载所有发票
        }
        
        // 选择客户时的联动处理
        document.getElementById('clientId').addEventListener('change', function() {
            const selectedClientId = this.value;
            if (selectedClientId) {
                // 加载该客户关联的合同
                loadClientContracts(selectedClientId);
            }
        });
        
        // 加载指定客户的合同
        function loadClientContracts(clientId, defaultContractId = null) {
            fetch(`/api/sales/contracts/list?clientId=${clientId}`)
                .then(response => response.json())
                .then(result => {
                    if (result.code === 200) {
                        const clientContracts = result.data;
                        
                        // 更新合同下拉框
                        const contractSelect = document.getElementById('contractId');
                        contractSelect.innerHTML = '<option value="">请选择关联合同</option>';
                        
                        clientContracts.forEach(contract => {
                            const option = document.createElement('option');
                            option.value = contract.id;
                            option.textContent = contract.contractNumber + ' - ' + contract.name;
                            contractSelect.appendChild(option);
                        });
                        
                        // 如果有默认选择的合同，设置它
                        if (defaultContractId) {
                            contractSelect.value = defaultContractId;
                        }
                        
                        // 触发合同选择事件以更新金额
                        if (contractSelect.value) {
                            contractSelect.dispatchEvent(new Event('change'));
                        }
                    } else {
                        console.error('加载客户合同失败:', result.message);
                    }
                })
                .catch(error => console.error('加载客户合同失败:', error));
        }
        
        // 选择合同时自动填充金额
        document.getElementById('contractId').addEventListener('change', function() {
            const selectedContractId = this.value;
            if (selectedContractId) {
                const selectedContract = contracts.find(contract => contract.id == selectedContractId);
                if (selectedContract) {
                    // 自动填充金额
                    document.getElementById('amount').value = selectedContract.amount;
                }
            }
        });
        
        // 日期验证 - 确保到期日期不早于发票日期
        document.getElementById('dueDate').addEventListener('change', function() {
            const issueDate = document.getElementById('issueDate').value;
            const dueDate = this.value;
            
            if (issueDate && dueDate && new Date(dueDate) < new Date(issueDate)) {
                alert('到期日期不能早于发票日期');
                this.value = '';
            }
        });
        
        // 自动生成发票编号
        function generateInvoiceNumber() {
            const prefix = 'INV';
            const date = new Date();
            const year = date.getFullYear().toString().substr(-2);
            const month = ('0' + (date.getMonth() + 1)).slice(-2);
            const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
            
            const invoiceNumber = `${prefix}${year}${month}-${random}`;
            document.getElementById('invoiceNumber').value = invoiceNumber;
        }
        
        // 发送发票提醒
        function sendInvoiceReminder(invoiceId) {
            if (confirm('确定要向客户发送发票提醒邮件吗？')) {
                fetch(`/api/sales/invoices/reminder/${invoiceId}`, {
                    method: 'POST'
                })
                .then(response => response.json())
                .then(result => {
                    if (result.code === 200) {
                        alert('发票提醒已发送');
                    } else {
                        alert('发送提醒失败: ' + result.message);
                    }
                })
                .catch(error => {
                    console.error('发送提醒失败:', error);
                    alert('系统错误，请稍后重试');
                });
            }
        }
        
        // 标记发票为已付款
        function markAsPaid(invoiceId) {
            if (confirm('确定要将此发票标记为已付款吗？')) {
                fetch(`/api/sales/invoices/mark-paid/${invoiceId}`, {
                    method: 'PUT'
                })
                .then(response => response.json())
                .then(result => {
                    if (result.code === 200) {
                        alert('发票已标记为已付款');
                        loadInvoices(); // 刷新列表
                    } else {
                        alert('操作失败: ' + result.message);
                    }
                })
                .catch(error => {
                    console.error('操作失败:', error);
                    alert('系统错误，请稍后重试');
                });
            }
        }
        
        // 导出发票为PDF
        function exportInvoicePdf(invoiceId) {
            window.location.href = `/api/sales/invoices/export-pdf/${invoiceId}`;
        }
        
        // 发送发票给客户
        function sendInvoiceToClient(invoiceId) {
            if (confirm('确定要将此发票发送给客户吗？')) {
                fetch(`/api/sales/invoices/send/${invoiceId}`, {
                    method: 'POST'
                })
                .then(response => response.json())
                .then(result => {
                    if (result.code === 200) {
                        alert('发票已发送给客户');
                        loadInvoices(); // 刷新列表
                    } else {
                        alert('发送失败: ' + result.message);
                    }
                })
                .catch(error => {
                    console.error('发送失败:', error);
                    alert('系统错误，请稍后重试');
                });
            }
        }
        
        // 检查逾期发票
        function checkOverdueInvoices() {
            fetch('/api/sales/invoices/check-overdue', {
                method: 'POST'
            })
            .then(response => response.json())
            .then(result => {
                if (result.code === 200) {
                    alert(`已检查逾期发票，${result.data}个发票已标记为逾期`);
                    loadInvoices(); // 刷新列表
                } else {
                    alert('操作失败: ' + result.message);
                }
            })
            .catch(error => {
                console.error('操作失败:', error);
                alert('系统错误，请稍后重试');
            });
        }
    </script>
</th:block> 